package com.linjiahao.userCenter.util;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.linjiahao.commonUtil.Redis.RedisService;
import com.linjiahao.commonUtil.base.RandomUtil;
import com.linjiahao.userCenter.common.BaseConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName MsmSendUtil
 * @Description: 阿里短信发送工具类
 * @Author linjiahao
 * @Date 29/12/2021
 **/
@Component
@Slf4j
public class MsmSendUtil {

    @Resource
    private RedisService redisService;

    @Value("${aliyuncs.accessKeyId}")
    private String accessKeyId;

    @Value("${aliyuncs.secret}")
    private String secret;

    @Value("${aliyuncs.signName}")
    private String signName;

    @Value("${aliyuncs.templateCode}")
    private String templateCode;


    public boolean sendMsm(String phone) {
        if (StringUtils.isEmpty(phone)) {
            return false;
        }
        Object o = redisService.get(String.format(BaseConstant.MSM_PHONE_CODE_KEY, phone));
        if(o!=null){
            log.info("手机号码：{}验证码还在缓存中，验证码为：{}",phone,o.toString());
            return true;
        }
        DefaultProfile profile =
                DefaultProfile.getProfile("default", accessKeyId, secret);
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        Map<String, Object> param = new HashMap<>();
        String code = RandomUtil.getFourBitRandom();
        param.put("code", code);
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", signName);
        request.putQueryParameter("TemplateCode", templateCode);
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(param));
        try {
            log.info("手机号码：{}进行短信号码发送，验证码为：{}",phone,code);
            CommonResponse response = client.getCommonResponse(request);
            boolean success = response.getHttpResponse().isSuccess();
            if(success){
                redisService.set(String.format(BaseConstant.MSM_PHONE_CODE_KEY, phone),code,60*60);
            }
            return success;
        } catch (Exception e) {
            log.error("发送短信失败：手机号码：{}",phone,e);
        }
        return false;
    }

}
